﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BL.Entities;
using EF;
using ApriBox.Mvc.UploadHelpers;

namespace ApriBox.Mvc.Controllers
{
    public class EditController : Controller
    {
        FSEntitiesRepository repository = new FSEntitiesRepository();
        public ActionResult LoadFile(int id)
        {
            File file = repository.GetFileById(id);

            string content = System.IO.File.ReadAllText(file.PhysicalPath);
            return Json(new { cont = content, path = file.PhysicalPath });
        }

        [HttpPost]
        public ActionResult SaveFile(string content, string path) 
        {
            using (System.IO.StreamWriter strw = new System.IO.StreamWriter(path)) 
            {
                strw.Write(content);
            }

            return Json(new { cont = content });
        }

        [HttpPost]
        public void changeFileName(int id, string type, string name)
        {
            if (name == "") return;
            else if (name[0] == '.') return;

            if (type == " file")
            {
                BL.Entities.File file = repository.GetFileById(id);

                if (file.Name == name) return;

                int parentFolderId = file.ParentId;

                IEnumerable<File> filesList = repository.GetFiles(parentFolderId);


                foreach (var f in filesList)
                {
                    if (f.Name == name)
                        name = Name.ChangeName(name, "file");
                }

                repository.writeFileName(id, name);

            }
            else 
            {
                BL.Entities.Folder folder = repository.GetFoldersById(id);

                if (folder.Name == name) return;

                int parentFolderId = folder.ParentId;

                IEnumerable<Folder> folders = repository.GetFolders(parentFolderId);

                foreach (Folder fol in folders)
                {
                    if (fol.Name == name)
                        name = Name.ChangeName(name);
                }

                repository.writeFolderName(id, name); 
            }
        }

    }
}
